package com.cloudbroker.bcs.platform.dav.middle.bizservice.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.configure.ConfigUtil;
import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;
import com.cloudbroker.bcs.common.validatioin.constants.ValidationErrorCodes;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.ClientErr;
import com.cloudbroker.bcs.platform.dav.bizapi.service.base.vo.HSBCPSVO;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.adpage.AdpageBizService;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.adpage.result.AdpageBrokerData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.adpage.result.AdpageData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.adpage.result.AdpageListResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.adpage.result.AdpageTenantData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.adpage.result.BrokerListData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.adpage.result.TenantListData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.adpage.vo.AdpageListForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.adpage.vo.AdpageUpdateParam;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.dav.middle.context.HSBCPSBizDataContext;
import com.cloudbroker.bcs.platform.dav.middle.entity.Adpage;
import com.cloudbroker.bcs.platform.dav.middle.entity.Broker;
import com.cloudbroker.bcs.platform.dav.middle.entity.Tenant;
import com.cloudbroker.bcs.platform.dav.middle.entityview.AdpageView;
import com.cloudbroker.bcs.platform.dav.middle.service.AdpageService;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerService;
import com.cloudbroker.bcs.platform.dav.middle.service.TenantService;

@Service
public class AdpageBizServiceImpl implements AdpageBizService {
    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(AdpageBizService.class);
    
    @Resource
    private BrokerService brokerService;
    
    @Resource
    private AdpageService adpageService;
    @Resource
    private TenantService tenantService;
    
    @Override
    public BrokerListData funcBrokerList(HSBCPSVO param) {
        BrokerListData brokerListData = new BrokerListData();
        List<Broker> brokerList = brokerService.getBrokerList();
        if (brokerList == null) {
            brokerList = new ArrayList<>();
        }
        List<AdpageBrokerData> dataList = new ArrayList<AdpageBrokerData>();
        for (Broker broker : brokerList) {
            AdpageBrokerData data = new AdpageBrokerData();
            data.setBroker_id(broker.getBroker_id());
            data.setBroker_name(broker.getBroker_name());
            data.setTenant_id(ValueUtil.getLong(broker.getTenant_id()));
            /*金币叫法配置*/
            String coinsName = ConfigUtil.getTenantConfig("tenant" + ValueUtil.getString(broker.getTenant_id())).get(
                    "tenant.id.coins.name", ConfigValues.COINS_NAME);
            data.setCoin_name(coinsName);
            dataList.add(data);
        }
        AdpageBrokerData b = new AdpageBrokerData();
        b.setBroker_id(0L);
        b.setTenant_id(0L);
        b.setBroker_name("默认图片");
        dataList.add(b);
        brokerListData.setData_list(dataList);
        return VOUtil.setSuccessResult(brokerListData);
    }

    @Override
    public AdpageListResult funcAdpageList(AdpageListForm param) {
        AdpageListResult adpageListResult = new AdpageListResult();
        List<AdpageView> adpageList = null;
        String broker_id = param.getBroker_id();
        Long brokerId = Long.valueOf(broker_id);

        String loading_img_url;
        String payStatus;
        String serviceTel;
        String viewpointPublicFlag = null;

        if (!brokerId.equals(0L)) {
            Broker broker = brokerService.get(broker_id);
            if (broker == null) {
                return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, AdpageListResult.class);
            }
            adpageList = adpageService.getByBrokerId(brokerId,broker.getTenant_id());
            loading_img_url = broker.getLoading_img_url();
            payStatus = String.valueOf(broker.getThird_pay_status());
            serviceTel = broker.getService_tel();
        }
        else
        {
            Integer tenantId = Integer.valueOf(param.getTenant_id());
            /*增加默认图片*/
            if(tenantId.equals(0))
            {
                adpageList = adpageService.getByBrokerId(0L,0);
                loading_img_url = "";
                payStatus = "";
                serviceTel = "";
            }
            else
            {
                Tenant tenant = tenantService.get(param.getTenant_id());
                if (tenant == null){
                    return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, AdpageListResult.class);
                }
                adpageList = adpageService.getByTenantId(tenantId);
                loading_img_url = tenant.getLoading_img_url();
                payStatus = tenant.getThird_pay_status();
                serviceTel = tenant.getService_tel();
                viewpointPublicFlag = tenant.getViewpoint_public_flag();
            }

        }
        adpageListResult.setData_list(getAdpageDataList(adpageList));
        adpageListResult.setLoading_img_url(loading_img_url);
        adpageListResult.setPay_status(payStatus);
        adpageListResult.setService_tel(serviceTel);
        adpageListResult.setViewpoint_public_flag(viewpointPublicFlag);
        return VOUtil.setSuccessResult(adpageListResult);
    }
    
    @Override
    public HSBCPSBackVO funcAdpageUpdate(AdpageUpdateParam param) {
        HSBCPSBackVO result = new HSBCPSBackVO();
        String broker_id = param.getBroker_id();
        Long brokerId = Long.valueOf(param.getBroker_id());
        Integer tenantId = null;
        /*broker_id 0 代表是多投顾 */
        if (!brokerId.equals(0L)) {
            Broker broker = brokerService.get(broker_id);
            if (broker == null) {
                return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, AdpageListResult.class);
            }
            tenantId = broker.getTenant_id();
            HSBCPSBizDataContext.setTenantId(tenantId);
            /*删除旧数据*/
            adpageService.deleteByBrokerId(brokerId);
            broker.setLoading_img_url(param.getLoading_img_url());
            if(!StringUtil.isEmpty(param.getPay_status())){
                broker.setThird_pay_status(Integer.parseInt(param.getPay_status()));
            }
            broker.setService_tel(param.getService_tel());
            brokerService.update(broker);
        }
        else{

            tenantId = Integer.valueOf(param.getTenant_id());
            /*默认图片设置 broker_id=0 && tenant_id = 0*/
            if(tenantId.equals(0))
            {
                /*删除旧数据*/
                adpageService.deleteByTenantId(tenantId);
            }
            else
            {
                Tenant tenant = tenantService.get(param.getTenant_id());
                if (tenant == null) {
                    return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, AdpageListResult.class);
                }
                /*删除旧数据*/
                adpageService.deleteByTenantId(tenantId);
                tenant.setLoading_img_url(param.getLoading_img_url());
                tenant.setThird_pay_status(param.getPay_status());
                tenant.setService_tel(param.getService_tel());
                tenant.setViewpoint_public_flag(param.getViewpoint_public_flag());
                tenantService.update(tenant);
            }

        }
        List<Adpage> pageList = null;
        try {
            pageList = JSONObject.parseArray(param.getData_list(), Adpage.class);
        } catch (Exception e) {
            return VOUtil.genErrorResult(ValidationErrorCodes.PARAM_MALFORMED, HSBCPSBackVO.class);
        }


        for (Adpage adpage : pageList) {
            adpage.setBroker_id(brokerId);
            adpage.setTenant_id(tenantId);
            adpageService.save(adpage);
        }
        return VOUtil.setSuccessResult(result);
    }
    
    @Override
    public AdpageListResult funcFansAdpageList(HSBCPSVO param) {
        AdpageListResult adpageListResult = new AdpageListResult();
        Long brokerId = HSBCPSBizDataContext.getBrokerId();
        Integer tenantId = HSBCPSBizDataContext.getTenantId();
        List<AdpageView> adpageList = null;
        /*没有brokerId 表示是多投顾登录；相反，表示单投顾登录*/
        if(brokerId == null)
        {
            adpageList = adpageService.getByTenantId(tenantId);
        }
        else
        {
            adpageList = adpageService.getByBrokerId(brokerId,tenantId);
        }

        adpageListResult.setData_list(getAdpageDataList(adpageList));
        return VOUtil.setSuccessResult(adpageListResult);
    }

    @Override
    public TenantListData funcTenantList(HSBCPSVO form) {
        TenantListData tenantListData = new TenantListData();
        //List<TenantInfo> tenantInfos = ConfigUtil.getTenantInfos();
        List<Tenant> tenantList = tenantService.queryUserfullTenantList();
        List<AdpageTenantData> adpageTenantDatas = new ArrayList<>();
        for(Tenant tenant : tenantList)
        {
            /*String name = StringUtil.isEmpty(tenant.getName()) ? tenant.getBranch_name() : tenant.getName();
            *//*排除无名无姓数据*//*
            if(StringUtil.isEmpty(name))
            {
                 continue;
            }*/

            AdpageTenantData adpageTenantData = new AdpageTenantData();
            adpageTenantData.setTenant_id(String.valueOf(tenant.getTenant_id()));
            String name = StringUtil.isEmpty(tenant.getName()) ? tenant.getBranch_name() : tenant.getName();
            adpageTenantData.setTenant_name(name);
            adpageTenantDatas.add(adpageTenantData);
        }
        tenantListData.setData_list(adpageTenantDatas);
        return VOUtil.setSuccessResult(tenantListData);
    }
    private List<AdpageData> getAdpageDataList(List<AdpageView> adpageList)
    {
        if(adpageList==null || adpageList.size()==0)
        {
            return null;
        }
        List<AdpageData> adpageListData = new ArrayList<AdpageData>();
        for (AdpageView adpage : adpageList) {
            AdpageData adpageData = new AdpageData();
            adpageData.setPage_img(adpage.getPage_img());
            adpageData.setPage_url(adpage.getPage_url());
            adpageListData.add(adpageData);
        }
        return adpageListData;
    }

}
